/* 

\s：匹配一个空白字符，包括空格、制表符、换页符和换行符。

*/

function IsValidColor(color) {
    let type = '';
    const firstLetter = color[0],
        firstThreeLetters = color.substring(0, 3).toLowerCase(),
        firstFourLetters = color.substring(0, 4).toLowerCase();

    // 下面“\\”代表转义的“\”
    if (firstThreeLetters === "rgb" && firstFourLetters !== "rgba") {
        //如果是rgb开头，200-249，250-255，0-199
        type = "^[rR][gG][Bb][\(]([\\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)[\\s]*,){2}[\\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)[\\s]*[\)]{1}$";
    } else if (firstFourLetters === "rgba") {
        // 如果是rgba开头，判断0-255:200-249，250-255，0-199 判断0-1：0 1 1.0 0.0-0.9
        type = "^[rR][gG][Bb][Aa][\(]([\\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?)[\\s]*,){3}[\\s]*(1|1.0|0|0.[0-9])[\\s]*[\)]{1}$";
    } else if (firstLetter === "#") {
        //六位或者三位
        type = "^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$"
    } else if (firstThreeLetters === "hsl" && firstFourLetters !== "hsla") {
        //判断0-360 判断0-100%(0可以没有百分号)
        type = "^[hH][Ss][Ll][\(]([\\s]*(2[0-9][0-9]|360｜3[0-5][0-9]|[01]?[0-9][0-9]?)[\\s]*,)([\\s]*((100|[0-9][0-9]?)%|0)[\\s]*,)([\\s]*((100|[0-9][0-9]?)%|0)[\\s]*)[\)]$";
    } else if (firstFourLetters === "hsla") {
        type = "^[hH][Ss][Ll][Aa][\(]([\\s]*(2[0-9][0-9]|360｜3[0-5][0-9]|[01]?[0-9][0-9]?)[\\s]*,)([\\s]*((100|[0-9][0-9]?)%|0)[\\s]*,){2}([\\s]*(1|1.0|0|0.[0-9])[\\s]*)[\)]$";
    } else {
        return false
    }

    const reg = new RegExp(type);
    return color.match(reg);
}

console.log(IsValidColor("#FFF"))
console.log(IsValidColor("#ABCDEF"))
console.log(IsValidColor("rgb(  200,255,99)"))
console.log(IsValidColor("rgba(123,233,99,0.5)"))
console.log(IsValidColor("hsl(0,0,100%)"))
console.log(IsValidColor("hsla(0,0,50%, 0)"))
console.log(IsValidColor("$FFF"))